package com.kssoft.ebd.spider.common;

import com.kssoft.ebd.spider.common.config.SpiderConfig;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Site;

import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CommonUtils {

    private static Logger logger=  LoggerFactory.getLogger(CommonUtils.class);

    /***
     * webMap缓存存储
     */
    public  static ConcurrentHashMap<PageModelType,WebDriver> webDriverHashMap = new ConcurrentHashMap<>();

    /***
     * cookies缓存
     */
    public  static ConcurrentHashMap<PageModelType, Set<Cookie>> webCookieHashMap = new ConcurrentHashMap<>();

    /***
     *HTML关联MAP
     */
    public  static ConcurrentHashMap<PageModelType,String> htmlMap = new ConcurrentHashMap<>();


    public static HashMap<String,Cookie> returnCookies(Set<Cookie> cookieSet){
        HashMap<String,Cookie> cookiesMap = new HashMap<>();
        Date expires = null;
        String domain = null;
        String path = null;
        for(Cookie cookie :cookieSet){
            if(cookie.getExpiry()!=null){
                logger.info("当前的expiry***:"+cookie.getExpiry().toString());
                expires = cookie.getExpiry();
            }
            if(cookie.getDomain()!=null){
                logger.info("当前的domian***:"+cookie.getDomain());
                domain= cookie.getDomain();
            }
            if(cookie.getPath()!=null){
                logger.info("当前的path***:"+cookie.getDomain());
                path= cookie.getPath();
            }
            logger.info("当前的value***:"+cookie.getValue());
            logger.info("当前的name***:"+cookie.getName());
            if(cookie.getName()!=null){
                Cookie valueCookies = new Cookie(cookie.getName(),cookie.getValue(),domain,path,expires);
                cookiesMap.put(cookie.getName(),valueCookies);
            }
        }
        return cookiesMap;
    }

    /**
     * 保存首页的Cookie
     * @param seleniumCookies
     * @throws IOException
     */
    public static void saveHomeCookies(Set<Cookie> seleniumCookies) throws IOException {
        saveCookies(PageModelType.Home, SpiderConfig.HOME_COOKIE_FILE_PATH, seleniumCookies);
    }

    /**
     *  保存直播关闭页的Cookie
     * @param seleniumCookies
     * @throws IOException
     */
    public static void saveCloseBroadcastCookies(Set<Cookie> seleniumCookies) throws IOException {
        saveCookies(PageModelType.CloseBroadcast, SpiderConfig.CLOSE_BROADCAST_COOKIE_FILE_PATH, seleniumCookies);
    }

    /**
     *  保存直播开启页的Cookie
     * @param seleniumCookies
     * @throws IOException
     */
    public static void saveStartBroadcastCookies(Set<Cookie> seleniumCookies) throws IOException {
        saveCookies(PageModelType.StartBroadcast, SpiderConfig.START_BROADCAST_COOKIE_FILE_PATH, seleniumCookies);
    }

    // 保存Cookie到内存和文件
    private static void saveCookies(PageModelType pageModelType, String COOKIE_FILE_PATH, Set<Cookie> seleniumCookies) throws IOException {
        CommonUtils.webCookieHashMap.put(pageModelType,seleniumCookies);
        // 获取所有Cookie
        Map<String, String> cookies = new HashMap<>();

        for (Cookie cookie : seleniumCookies) {
            cookies.put(cookie.getName(), cookie.getValue());
            System.out.println("获取Cookie: " + cookie.getName() + "=" + cookie.getValue());
        }

        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(COOKIE_FILE_PATH))) {
            oos.writeObject(cookies);
            System.out.println("Cookie已保存到: " + COOKIE_FILE_PATH);
        }
    }

    // 从文件加载Cookie
    @SuppressWarnings("unchecked")
    public static Site getCookieToSite(Site SITE, PageModelType pageModelType, String COOKIE_FILE_PATH) throws IOException, ClassNotFoundException, NullCookiesException {

        if(CommonUtils.webCookieHashMap.containsKey(pageModelType)){
            Set<Cookie> cookies = CommonUtils.webCookieHashMap.get(pageModelType);
            if(cookies != null && cookies.size() > 0){
                cookies.forEach(cookie -> SITE.addCookie(cookie.getName(), cookie.getValue()));
            } else {
                throw new NullCookiesException("cookies is null");
            }
            return SITE;
        } else {
            Map<String, String> cookies = (Map<String, String>) new ObjectInputStream(
                    new FileInputStream(COOKIE_FILE_PATH)).readObject();
            System.out.println("从文件加载了 " + cookies.size() + " 个Cookie");
            if(cookies != null && cookies.size() > 0){

                cookies.forEach((k, v) -> SITE.addCookie(k, v));
            } else {
                throw new NullCookiesException("cookies is null");
            }
        }
        SITE.setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36");
        return SITE;
    }

    /**
     * 获取首页的Cookie
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     * @throws NullCookiesException
     */
    public static Map<String, String> getHomeCookies() throws IOException, ClassNotFoundException, NullCookiesException {
            return CommonUtils.getCookies(PageModelType.Home, SpiderConfig.HOME_COOKIE_FILE_PATH);
    }

    /**
     * 获取直播关闭页的Cookie
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     * @throws NullCookiesException
     */
    public static Map<String, String> getCloseBroadcastCookies() throws IOException, ClassNotFoundException, NullCookiesException {
            return CommonUtils.getCookies(PageModelType.CloseBroadcast, SpiderConfig.CLOSE_BROADCAST_COOKIE_FILE_PATH);
    }

    /**
     * 获取直播开启页的Cookie
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     * @throws NullCookiesException
     */
    public static Map<String, String> getStartBroadcastCookies() throws IOException, ClassNotFoundException, NullCookiesException {
            return CommonUtils.getCookies(PageModelType.StartBroadcast, SpiderConfig.START_BROADCAST_COOKIE_FILE_PATH);
    }

    // 从文件加载Cookie
    @SuppressWarnings("unchecked")
    public static Map<String, String> getCookies(PageModelType pageModelType, String COOKIE_FILE_PATH) throws IOException, ClassNotFoundException, NullCookiesException {

        if(CommonUtils.webCookieHashMap.containsKey(pageModelType)){
            Set<Cookie> cookies = CommonUtils.webCookieHashMap.get(pageModelType);
            if(cookies != null && cookies.size() > 0){

            } else {
                throw new NullCookiesException("cookies is null");
            }
            Map<String, String> cookieMap = new HashMap<>();
            cookies.forEach(cookie -> cookieMap.put(cookie.getName(), cookie.getValue()));
            return cookieMap;
        } else {
            Map<String, String> cookies = (Map<String, String>) new ObjectInputStream(
                    new FileInputStream(COOKIE_FILE_PATH)).readObject();
            System.out.println("从文件加载了 " + cookies.size() + " 个Cookie");
            if(cookies.isEmpty()){
                throw new NullCookiesException("cookies is null");
            }
            return cookies;
        }
    }

    // 根据类型 移除 内存和文件 Cookie
    public static void removeCookies(PageModelType pageModelType) throws IOException {
        CommonUtils.webCookieHashMap.remove(pageModelType);
        if(pageModelType == PageModelType.Home){
            FileUtils.deleteQuietly(new File(SpiderConfig.HOME_COOKIE_FILE_PATH));

        }else if (pageModelType == PageModelType.StartBroadcast){
            FileUtils.deleteQuietly(new File(SpiderConfig.START_BROADCAST_COOKIE_FILE_PATH));
        }else if(pageModelType == PageModelType.CloseBroadcast){
            FileUtils.deleteQuietly(new File(SpiderConfig.CLOSE_BROADCAST_COOKIE_FILE_PATH));
        }
    }
}
